const svg = d3.select('svg');

const width = +svg.attr('width');
const height = +svg.attr('height');

const render = data => {
  const title = 'cars : horsepower vs weight';
  const xAxisLabel = 'HorsePower';
  const yAxisLabel = 'Weight';
	
  const xValue = d => d.horsepower;
  const yValue = d => d.weight;
  const margin = { top: 80, bottom: 30, left: 100, right: 20};
  const innerWidth = width - margin.left - margin.right;
  const innerHeight = height - margin.top - margin.bottom;
  
  const circleRadius = 8;
  
  const xScale = d3.scaleLinear()
    .domain(d3.extent(data, xValue))
	.range([0, innerWidth])
	.nice();
  
  const yScale = d3.scaleLinear()
    .domain([d3.max(data, yValue), d3.min(data, yValue)]) //大小顺序决定了x轴排序,小在上,大在下
	.range([0, innerHeight]);
	//.padding(0.2);//轴间距
	
  
  const g = svg.append('g')
    .attr('transform',`translate(${margin.left},${margin.bottom})`);
  
  const yAxis = d3.axisLeft(yScale)
    .tickSize(-innerWidth);
  
  const yAxisGroup = g.append('g').call(yAxis);
  yAxisGroup.selectAll('.domain')
	.remove();
  yAxisGroup.append('text')
    .attr('fill', 'black')
    .attr('x', -innerHeight/2)
	.attr('y', -50)
    .attr('transform',`rotate(-90)`)
	.attr('text-anchor', 'middle')
	.text(yAxisLabel);
  
  //格式化x轴数据
  const xAxis = d3.axisBottom(xScale)
	//添加网格线
	.tickSize(-innerHeight);
 
  const xAxisGroup = g.append('g').call(xAxis)
    .attr('transform',`translate(0, ${innerHeight})`);
  //去除x轴轴线
  xAxisGroup.selectAll('.domain').remove();
  //添加x轴名称
  xAxisGroup.append('text')
    .attr('fill', 'black')
    .attr('y', 40)
	.attr('x', innerWidth/2)
	.text(xAxisLabel);

  
  g.selectAll('circle').data(data)
    .enter().append('circle')
      .attr('cy', d => yScale(yValue(d)))
      .attr('cx', d => xScale(xValue(d)))
      .attr('r', circleRadius)
	  .append('title')
	  .text(function(d){
	    return `${d.name} : ${d.horsepower}PS`
	  });
	  
  g.append('text')
    .attr('y', -10)
	.attr('x',innerWidth/3)
	.text(title);
}

d3.csv('auto-mpg.csv').then( data => {
  data.forEach(d => {
    d.acceleration = +d.acceleration;
	d.cylinders = +d.cylinders;
	d.displacement = +d.displacement;
	d.horsepower = +d.horsepower;
	d.mpg = +d.mpg;
	d.weight = +d.weight;
	d.year = +d.year;
  });
  
  const readyData = function(){
	var d = [];
	var len = 10000;
	var x = 0;
	while (len--) {
		x = (Math.random() * 10).toFixed(3) - 0;
		d.push([
			x,
			//Math.random() * 10
			(Math.cos(x) - x * (len % 2 ? 0.1 : -0.1) * Math.random()).toFixed(3) - 0
		]);
	}
	//console.log(d)
	return d;
  }
  
  
  
  render(data);
});